package org.example.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MyBatis-Plus 配置类
 */
@Configuration
public class MybatisPlusConfig {

    /**
     * 配置 MyBatis-Plus 插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 元数据自动填充：插入时填充 createdAt
     */
    @Bean
    public MetaObjectHandler auditMetaObjectHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                try {
                    // 若实体包含 createdAt 且当前为空，则填充为当前时间
                    Object createdAt = this.getFieldValByName("createdAt", metaObject);
                    if (createdAt == null) {
                        this.strictInsertFill(metaObject, "createdAt", java.time.LocalDateTime.class, java.time.LocalDateTime.now());
                    }
                } catch (Exception ignore) { }
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                // 目前仅需插入填充，如后续增加 updatedAt 可在此处理
            }
        };
    }
}